package me.hunche.app.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.zip.ZipInputStream;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

public final class HttpClientUtil {

	private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
	
	public final static String CONTENTTYPE = "Content-Type";
	public final static String CONTENTTYPE_UTF8 = "text/xml; charset=UTF-8";

	private final static int DEFAULT_BUFFER_SIZE = 8 * 1024;
	private final static int CONNECTION_TIMEOUT = 60000;
	
	private ArrayList<NameValuePair> params;
	private ArrayList<NameValuePair> headers;
	private String url;
	public int responseCode;
	public String message;
	public String response;
	public ZipInputStream zipInputStream;

	public HttpClientUtil(String url) {
		this.url = url;
		params = new ArrayList<NameValuePair>();
		headers = new ArrayList<NameValuePair>();
	}

	public void addParam(String name, String value) {
		params.add(new BasicNameValuePair(name, value));
	}

	public void addHeader(String name, String value) {
		headers.add(new BasicNameValuePair(name, value));
	}

	/**
	 * execute HTTP method
	 * @param method
	 * @param resultType
	 * @throws Exception
	 */
	public void execute(ResuestMethod method)
			throws Exception {
		switch (method) {
		case GET: {
			StringBuffer sBuffer = new StringBuffer();
			if (!params.isEmpty()) {
				sBuffer.append("?");
				for (NameValuePair param : params) {
					if (sBuffer.length() > 1) {
						sBuffer.append("&");
					}
					sBuffer.append(param.getName())
							.append("=")
							.append(URLEncoder.encode(param.getValue(),
									HTTP.UTF_8));
				}
			}

			HttpGet request = new HttpGet(url + sBuffer.toString());
			for (NameValuePair head : headers) {
				request.addHeader(head.getName(), head.getValue());
			}

			executeRequest(request, url);
			break;
		}
		case POST: {
			HttpPost request = new HttpPost(url);
			for (NameValuePair head : headers) {
				request.addHeader(head.getName(), head.getValue());
			}

			if (!params.isEmpty()) {
				request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}

			executeRequest(request, url);
			break;
		}
		case PUT: {
			HttpPut request = new HttpPut(url);

			for (NameValuePair head : headers) {
				request.addHeader(head.getName(), head.getValue());
			}

			if (!params.isEmpty()) {
				request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}

			executeRequest(request, url);
			break;
		}
		case DELETE: {
			StringBuffer sBuffer = new StringBuffer();
			if (!params.isEmpty()) {
				sBuffer.append("?");
				for (NameValuePair param : params) {
					if (sBuffer.length() > 1) {
						sBuffer.append("&");
					}
					sBuffer.append(param.getName())
							.append("=")
							.append(URLEncoder.encode(param.getValue(),
									HTTP.UTF_8));
				}
			}

			HttpDelete request = new HttpDelete(url + sBuffer.toString());

			for (NameValuePair head : headers) {
				request.addHeader(head.getName(), head.getValue());
			}

			executeRequest(request, url);
			break;
		}
		}
	}

	/**
	 * execute HTTP request
	 * @param request
	 * @param url
	 * @param resultType
	 */
	private void executeRequest(HttpUriRequest request, String url) {
		HttpClient client = this.getHttpClient();
		
		// TODO: development mode for HTTPS
        WebClientDevWrapper clientWrapper = new WebClientDevWrapper();
        clientWrapper.wrapClient(client);
		
		// TODO: development mode for HTTP proxy
//		 HttpHost proxy = new HttpHost("web-proxy.usa.hp.com", 8080);
//		 client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
//		 proxy);

		HttpResponse httpResponse;
		try {
			httpResponse = client.execute(request);
			responseCode = httpResponse.getStatusLine().getStatusCode();
			message = httpResponse.getStatusLine().getReasonPhrase();
			
			logger.debug("responseCode is " + responseCode);
			
			if (responseCode == 200) {
				HttpEntity entity = httpResponse.getEntity();
				if (entity != null) {
					InputStream instream = entity.getContent();
					response = convertStreamToString(instream);
					instream.close();
				}
			} else {
				response = null;
			}
		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		} catch (IOException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private HttpClient getHttpClient() {
		return createHttpClient();
	}

	/**
	 * create HTTP client
	 * @return
	 */
	public static HttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setSocketBufferSize(params, DEFAULT_BUFFER_SIZE);

		HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);

		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		registry.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));

		ClientConnectionManager connectionManager = new SingleClientConnManager(
				params, registry);
		return new DefaultHttpClient(connectionManager, params);
	}
	
	public enum ResuestMethod {
		GET, PUT, POST, DELETE
	}
	
	/**
	 * convert stream to string
	 * @param is
	 * @return
	 */
	private String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/* 
	This code is public domain: you are free to use, link and/or modify it in any way you want, for all purposes including commercial applications.  
	*/
	class WebClientDevWrapper { 
	  
	    public HttpClient wrapClient(HttpClient base) { 
	        try { 
	            SSLContext ctx = SSLContext.getInstance("TLS"); 
	            X509TrustManager tm = new X509TrustManager() { 
	  
	                public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { 
	                } 
	  
	                public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { 
	                } 
	  
	                public X509Certificate[] getAcceptedIssuers() { 
	                    return null; 
	                } 
	            }; 
	            X509HostnameVerifier verifier = new X509HostnameVerifier() { 
	  
	                public void verify(String string, SSLSocket ssls) throws IOException { 
	                } 
	  
//	                @Override
	                public void verify(String string, X509Certificate xc) throws SSLException { 
	                } 
	  
//	                @Override
	                public void verify(String string, String[] strings, String[] strings1) throws SSLException { 
	                } 

//					@Override
					public boolean verify(String arg0, SSLSession arg1) {
						return true;
					} 
	            }; 
	            ctx.init(null, new TrustManager[]{tm}, null); 
	            SSLSocketFactory ssf = new SSLSocketFactory(ctx); 
	            ssf.setHostnameVerifier(verifier); 
	            ClientConnectionManager ccm = base.getConnectionManager(); 
	            SchemeRegistry sr = ccm.getSchemeRegistry(); 
	            sr.register(new Scheme("https", ssf, 443)); 
	            return new DefaultHttpClient(ccm, base.getParams()); 
	        } catch (Exception ex) { 
	            ex.printStackTrace(); 
	            return null; 
	        } 
	    } 
	}

}
